package cn.wildfire.chat.app.extendsion.utils;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.security.InvalidParameterException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by HEKE, 2019/10/14 16:05
 * TODO 文件类型操作对象
 */
public class VariableFilesUtils {

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(java.io.File file) {
        if (!file.exists()) {
            return 0;
        }
        if (file.isFile()) {
            return file.length();
        }
        if (file.listFiles() == null || file.list().length == 0) {
            return 0;
        }
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
            return size;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 转换文件大小
     *
     * @param fileSize
     */
    public static String toFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024) {
            fileSizeString = "";
        } else if (fileSize < 1024 * 1024) {
            fileSizeString = "0" + df.format((double) fileSize / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileSize / 1048576) + "MB";
        }
        return fileSizeString;
    }

    /**
     * 创建文件或者目录
     *
     * @param path
     * @param isDirectory
     */
    public static int simpleBuilderSync(String path, boolean isDirectory) {
        if (path == null || path.trim().length() == 0) {
            return -1;
        }
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.setReadable(true);
                file.setWritable(true);
                if (isDirectory) {
                    file.mkdirs();
                } else {
                    file.createNewFile();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 创建目录或者文件，可填写内容
     *
     * @param path
     * @param content
     * @param isDirectory
     * @param onNormalOperateStatusListener
     */
    public static void asyncCreateSingle(String path, String content, boolean isDirectory, OnNormalOperateStatusListener onNormalOperateStatusListener) {
        if (path == null || path.trim().length() == 0) {
            return;
        }
        new AsyncTask<String, Integer, Integer>() {
            @Override
            protected Integer doInBackground(String... params) {
                String path = params[0];
                String content = params[1];
                try {
                    simpleBuilderSync(path, isDirectory);
                    if (content != null && content.trim().length() > 0) {
                        FileOutputStream fos = new FileOutputStream(new File(path));
                        fos.write(content.getBytes());
                        fos.flush();
                        fos.close();
                    }
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return -1;
            }

            @Override
            protected void onPostExecute(Integer r) {
                super.onPostExecute(r);
                if (onNormalOperateStatusListener != null) {
                    onNormalOperateStatusListener.resp(r == 0);
                }
            }

        }.execute(path, content);
    }

    /**
     * 创建目录或者文件
     *
     * @param pathList
     * @param contentList
     * @param fileDirectionList
     * @param onNormalOperateStatusListener
     */
    public static void asyncCreateMuch(final List<String> pathList, final List<String> contentList, final List<Boolean> fileDirectionList
            , OnNormalOperateStatusListener onNormalOperateStatusListener) {
        if (pathList == null || fileDirectionList == null)
            return;
        if (pathList.size() != fileDirectionList.size()) {
            throw new InvalidParameterException("The pathList size must be the same of fileDirectionList !");
        }
        new AsyncTask<String, Integer, Integer>() {
            @Override
            protected Integer doInBackground(String... params) {
                try {
                    int size = pathList.size();
                    for (int i = 0; i < size; i++) {
                        String path = pathList.get(i);
                        boolean isDirectory = fileDirectionList.get(i);
                        simpleBuilderSync(path, isDirectory);
                    }
                    if (contentList != null && contentList.size() > 0) {
                        int contentIndex = 0;
                        for (int i = 0; i < size; i++) {
                            String path = pathList.get(i);
                            boolean isDirectory = fileDirectionList.get(i);
                            if (!isDirectory) {
                                if (contentIndex >= contentList.size()) {
                                    break;
                                }
                                String content = contentList.get(contentIndex);
                                FileOutputStream fos = new FileOutputStream(new File(path));
                                fos.write(content.getBytes());
                                fos.flush();
                                fos.close();
                                contentIndex++;
                            }
                        }
                    }
                    return 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return -1;
            }

            @Override
            protected void onPostExecute(Integer r) {
                super.onPostExecute(r);
                if (onNormalOperateStatusListener != null) {
                    onNormalOperateStatusListener.resp(r == 0);
                }
            }
        }.execute();
    }

    /**
     * 查询目录下所有文件
     */
    public static List<File> checkDirectoryAllFiles(String directoryPath) {
        if (TextUtils.isTextEmpty(directoryPath)) {
            return null;
        }
        File file = new File(directoryPath);
        if (!file.exists()) {
            return null;
        }
        List<File> fileList = new ArrayList<>();
        File[] files = file.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                if (f.isFile()) {
                    fileList.add(f);
                } else {
                    List<File> directoryFileList = checkDirectoryAllFiles(f.getAbsolutePath());
                    if (directoryFileList != null && directoryFileList.size() > 0) {
                        fileList.addAll(directoryFileList);
                    }
                }
            }
        }
        return fileList;
    }

    /**
     * 异步执行删除目录
     *
     * @param directoryPath
     * @param onDeleteFilesListener
     */
    public static void deleteDirectoryAsync(String[] directoryPath, final OnDeleteFilesListener onDeleteFilesListener) {
        if (directoryPath == null || directoryPath.length == 0) {
            return;
        }
        new AsyncTask<String[], Integer, String>() {

            int total;
            int progress;

            @Override
            protected String doInBackground(String[]... params) {
                String[] paths = params[0];
                List<File> fileList = new ArrayList<>();
                try {
                    for (String path : paths) {
                        List<File> pathList = checkDirectoryAllFiles(path);
                        if (pathList != null && pathList.size() > 0) {
                            fileList.addAll(pathList);
                        }
                    }
                    if (fileList != null && fileList.size() > 0) {
                        total = fileList.size();
                        progress = 1;
                        for (int i = 0; i < fileList.size(); i++) {
                            File file = fileList.get(i);
                            file.delete();
                            progress++;
                            int ratioInt = (int) ((progress * 1f / total) * 100);
                            publishProgress(ratioInt);
                        }
                        return "1";
                    } else {
                        return "0";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "-1";
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                if (onDeleteFilesListener != null) {
                    onDeleteFilesListener.progress(values[0]);
                }
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (onDeleteFilesListener != null) {
                    boolean error = "-1".equals(s);
                    onDeleteFilesListener.result(!error, error);
                }
            }
        }.execute(directoryPath);
    }

    /**
     * 写入序列化对象至指定路径下
     *
     * @param cachePath
     * @param pushObj
     */
    public static void pushSync(String cachePath, Object pushObj) {
        if (cachePath == null || cachePath.trim().length() == 0 || pushObj == null) {
            return;
        }
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create by HEKE, 2019/10/14 16:11
     * TODO 常态情况下使用回调运行结果状态
     */
    public interface OnNormalOperateStatusListener {
        void resp(boolean integrated);
    }

    /**
     * 带进度的删除回调接口
     */
    public interface OnDeleteFilesListener {
        void progress(int progress);

        void result(boolean success, boolean error);
    }

}
